<template>
  <div class="random-tag-generator">
    <div class="config-manage">
      <div style="display: flex;" class="mb10">
        <el-select size="default" v-model="selectedConfigId" :placeholder="$t('message.random.selectPreset')" class="mr10"
          @change="handleConfigSelect">
          <el-option v-for="config in customConfigs" :key="config.id" :label="config.name" :value="config.id" />
        </el-select>
        <el-button size="default" type="primary" @click="showSaveDialog" icon="DocumentAdd">{{
          $t('message.random.saveConfig') }}</el-button>
        <el-button size="default" type="danger" @click="deleteConfig" icon="Delete">{{ $t('message.random.deleteConfig')
          }}</el-button>
        <el-button size="default" type="success" icon="MagicStick" @click="generateTags" :loading="loading">{{
          $t('message.random.generateTags') }}</el-button>
        <el-button size="default" type="info" icon="Refresh" @click="clearAll">{{ $t('message.common.clearAll')
          }}</el-button>
      </div>
    </div>
    <!-- 条件配置区域 -->
    <div class="config-area">
      <div v-for="(condition, index) in conditions" :key="index" class="condition-item">
        <el-cascader v-model="condition.path" :options="cascaderOptions" :props="cascaderProps"
          :placeholder="$t('message.random.selectType')" clearable filterable @change="handleCascaderChange(index)"
          class="cascader" :disabled="condition.locked" />

        <el-input-number v-model="condition.size" :min="1" :max="20" controls-position="right"
          :placeholder="$t('message.random.selectSize')" class="size-input" :disabled="condition.locked" />

        <!-- 锁定开关 -->
        <el-switch v-model="condition.locked" active-color="#ff4949" inactive-color="#13ce66" :active-value="true"
          :inactive-value="false" style="margin-left: 10px;" :title="$t('message.random.lockCondition')"
          @change="(val) => handleLockChange(index, val)" />

        <el-button size="default" type="danger" icon="Delete" circle @click="removeCondition(index)" class="remove-btn" />
      </div>

      <el-button size="default" type="primary" icon="Plus" @click="addCondition" class="add-btn">{{
        $t('message.random.addCondition') }}</el-button>
    </div>

    <!-- 操作按钮 -->
    <div class="action-area">
      <el-button size="default" @click="cycleRandom" type="primary" :disabled="generationStore.isJob">{{
        $t('message.random.cycleRandom') }}</el-button>
      <el-switch v-model="generationStore.cycleRandomFlag"></el-switch>
      <el-button size="default" @click="cycleRandomV3" type="primary" :disabled="generationStore.isJob">{{
        $t('message.random.cycleRandomV3') }}</el-button>
      <el-switch v-model="generationStore.cycleRandomFlagV3"></el-switch>
      <el-tag>{{ $t('message.random.CurrentQueue') + currentTagIndex + " / " + allSequentialTags.length }}</el-tag>
    </div>

    <!-- 结果展示 -->
    <div v-if="results.length" class="result-area">
      <div v-for="(groupResult, index) in results" :key="index" class="result-group">
        <el-card class="result-card">
          <template #header>
            <div class="card-header">
              <span class="group-name">{{ groupResult.group }}</span>
              <span v-if="groupResult.name" class="sub-group">/ {{ groupResult.name }}</span>
              <el-tag type="info" effect="dark" round>
                {{ $t('message.random.matched') }}: {{ groupResult.size }}
              </el-tag>
            </div>
          </template>

          <div class="tag-list">
            <el-tag v-for="(tag, tagIndex) in groupResult.tags" :key="tagIndex" type="success" effect="dark" round
              class="tag-item" @click="copyTag(tag)">
              {{ tag.label }} ({{ tag.value }})
            </el-tag>

            <div v-if="!groupResult.tags.length" class="empty-tip">
              {{ $t('message.random.noMatched') }}
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <el-dialog v-model="saveDialogVisible" title="保存配置" width="30%">
      <el-form>
        <el-form-item label="配置名称">
          <el-input v-model="newConfigName" placeholder="请输入配置名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="default" @click="saveDialogVisible = false">取消</el-button>
        <el-button size="default" type="primary" @click="saveCustomConfig">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="RandomTag">
import { ref, onMounted, PropType } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { CascaderOption, CascaderProps } from 'element-plus'
import { useGenerationStore } from '@renderer/stores/useGenerationStore'
import { tagApi } from '@renderer/api/tags'
import { commonApi } from '@renderer/api/common'
import { useExPrompt } from '@renderer/stores/useExPrompt'

interface RandomConfig {
  class_type: string;
  value: [number, number];
  favorite: boolean | null;
  disliked: boolean | null;
  min_rating: number | null;
  max_rating: number | null;
}

// 定义完整的 random 对象类型，新增cloth类别
interface RandomObject {
  style: RandomConfig;
  collect: RandomConfig;
  action: RandomConfig;
  cloth: RandomConfig; // 新增cloth类别
}

const generationStore = useGenerationStore()
const exPromptStore = useExPrompt()
let intervalId: ReturnType<typeof setTimeout> | null = null

const emit = defineEmits(['tags-generated', 'cycle-random']);
const props = defineProps({
  random: {
    type: Object as PropType<RandomObject>,
    required: true,
    default: () => ({
      style: {
        class_type: 'style',
        value: [0, 0],
        favorite: null,
        disliked: null,
        min_rating: null,
        max_rating: null
      },
      collect: {
        class_type: 'collect',
        value: [0, 0],
        favorite: null,
        disliked: null,
        min_rating: null,
        max_rating: null
      },
      action: {
        class_type: 'action',
        value: [0, 0],
        favorite: null,
        disliked: null,
        min_rating: null,
        max_rating: null
      },
      // 新增cloth默认配置
      cloth: {
        class_type: 'cloth',
        value: [0, 0],
        favorite: null,
        disliked: null,
        min_rating: null,
        max_rating: null
      }
    })
  }
});

interface CustomConfig {
  id: string
  name: string
  conditions: Condition[]
  createTime: number
}

interface Condition {
  path: string[]
  group: string
  name?: string | null;
  size: number
  locked?: boolean  // 新增锁定状态
  currentTags?: Array<{ value: string; label: string }> // 存储当前生成的标签
}

interface TagResult {
  group: string
  name?: string
  size: number
  tags: Array<{ value: string; label: string }>
}

// 组件状态
const cascaderOptions = ref<CascaderOption[]>([])
const conditions = ref<Condition[]>([])
const results = ref<TagResult[]>([])
const loading = ref(false)

const currentTagIndex = ref(0)
const allSequentialTags = ref<string[]>([])

// 级联选择器配置
const cascaderProps: CascaderProps = {
  checkStrictly: true,
  emitPath: true,
  expandTrigger: 'hover',
  value: 'value',
  label: 'label'
}

// 初始化加载分类数据
onMounted(async () => {
  try {
    const res = await tagApi().getCategories();

    const groupMap = new Map<string, CascaderOption>()
    res.data.data.forEach((item: { group: string; name: string }) => {
      if (!groupMap.has(item.group)) {
        groupMap.set(item.group, {
          path: [item.group],
          value: item.group,
          label: item.group,
          children: []
        })
      }
      const groupNode = groupMap.get(item.group)
      if (groupNode?.children) {
        groupNode.children.push({
          path: [item.group, item.name],
          value: item.name,
          label: item.name
        })
      }
    })

    cascaderOptions.value = Array.from(groupMap.values())
  } catch (error) {
    ElMessage.error('分类数据加载失败')
  }
})

// 处理级联选择变化
const handleCascaderChange = (index: number) => {
  const path = conditions.value[index].path
  conditions.value[index].group = path?.[0] || ''
  conditions.value[index].name = path?.length > 1 ? path[1] : undefined
  // 清空当前标签
  conditions.value[index].currentTags = []
}

// 添加条件
const addCondition = () => {
  conditions.value.push({
    path: [],
    group: '',
    size: 3,
    locked: false,  // 默认未锁定
    currentTags: [] // 初始化空标签
  })
}

// 删除条件
const removeCondition = (index: number) => {
  conditions.value.splice(index, 1)
}

// 处理锁定状态变化
const handleLockChange = (index: number, locked: boolean) => {
  // 解锁时保留当前标签
  if (!locked && !conditions.value[index].currentTags?.length) {
    // 如果解锁且没有当前标签，在下次生成时生成
  }
}

// 生成标签 - 锁定条件使用当前标签
const generateTags = async () => {
  try {
    loading.value = true
    const requestConditions = conditions.value
      .filter(c => c.group && !c.locked)
      .map(c => ({
        group: c.group,
        name: c.name,
        size: c.size
      }))

    if (requestConditions.length === 0) {
      // 如果所有条件都锁定了，直接使用当前标签
      buildResultsFromCurrentTags()
      return
    }

    // 2. 调用批量随机标签接口
    const { data } = await tagApi().batchGenerateTags(requestConditions);

    // 3. 更新未锁定条件的当前标签
    let resultIndex = 0
    conditions.value.forEach(condition => {
      if (!condition.locked && condition.group) {
        // 使用批量接口返回的结果更新当前标签
        condition.currentTags = data.results[resultIndex]?.tags || []
        resultIndex++
      }
    })
    // 4. 构建展示结果
    buildResultsFromCurrentTags()
  } catch (error) {
    ElMessage.error('标签生成失败')
  } finally {
    loading.value = false
  }
}

// 从当前标签构建结果
const buildResultsFromCurrentTags = () => {
  results.value = conditions.value
    .filter(c => c.group && c.currentTags?.length)
    .map(c => ({
      group: c.group,
      name: c.name || undefined,
      size: c.currentTags?.length || 0,
      tags: c.currentTags || []
    }))

  // 合并所有标签
  const allTags = results.value
    .flatMap(groupResult => groupResult.tags.map(tag => tag.value))
    .join(',')

  if (allTags) {
    emit('tags-generated', allTags)
  } else {
    ElMessage.warning('没有生成有效的标签')
  }
}

// 更新类型定义，添加cloth选项
const getCommonRandom = async (type: 'style' | 'collect' | 'action' | 'cloth') => {
  const search = props.random[type]
  const res = await commonApi().getRandomChioce(search);

  const result = res.data.result;
  const tags = result.tags.split('Negative prompt')[0];

  exPromptStore.updateState({
    [type]: {
      ...result,
      tags,
      search
    }
  });
};

const cycleRandom = async () => {
  generationStore.cycleRandomFlag = true
  const generateWithInterval = async () => {
    if (!generationStore.cycleRandomFlag) return
    try {
      await generateTags()
      await generationStore.generateImages()
    } catch (error) {
      ElMessage.error('标签生成失败')
      generationStore.cycleRandomFlag = false
    }

    // 设置下次生成间隔
    intervalId = setTimeout(generateWithInterval, 200)
  }
  generateWithInterval()
}

const cycleRandomV3 = async () => {
  // 只使用未锁定的条件
  const unlockedConditions = conditions.value.filter(c => !c.locked && c.group);
  if (!unlockedConditions.length) {
    ElMessage.warning('请先配置未锁定的条件')
    return
  }

  generationStore.cycleRandomFlagV3 = true
  currentTagIndex.value = 0
  const tags = await generateSequentialTags();
  if (!tags.length) {
    generationStore.cycleRandomFlagV3 = false
    return
  }
  allSequentialTags.value = tags
  try {
    for (const [index, item] of allSequentialTags.value.entries()) {
      currentTagIndex.value = index + 1
      emit('tags-generated', item)
      try {
        await generationStore.generateComfyUIImagesV2()
      } catch (e) {
        ElMessage.error(`第 ${currentTagIndex.value} 个提示词生成失败: ${e.message}`)
      }
      // 添加间隔避免请求过快
      if (!generationStore.cycleRandomFlagV3) break;
      await new Promise(r => setTimeout(r, 500))
    }
  }
  catch (error) {
    ElMessage.error('标签生成失败')
  } finally {
    generationStore.cycleRandomFlagV3 = false
    currentTagIndex.value = 0
  }
}

// 生成顺序标签
const generateSequentialTags = async () => {
  try {
    loading.value = true
    // 使用第一个未锁定条件
    const condition = conditions.value.find(c => !c.locked && c.group)
    if (!condition) {
      ElMessage.warning('请至少配置一个有效且未锁定的条件')
      return []
    }

    const { data } = await tagApi().batchGenerateSequentialTags({
        group: condition.group,
        name: condition.name,
        size: condition.size
    })

    results.value = data.results
    const allTags = results.value
      .flatMap(groupResult => groupResult.tags.map(tag => tag.value))
    return allTags
  } catch (error) {
    ElMessage.error('标签生成失败')
    return []
  } finally {
    loading.value = false
  }
}

// 清空所有
const clearAll = () => {
  emit('tags-generated', '')
  conditions.value = []
  results.value = []
}

// 复制标签
const copyTag = async (tag: { value: string; label: string }) => {
  try {
    await navigator.clipboard.writeText(tag.value)
    ElMessage.success(`已复制: ${tag.value}`)
  } catch (err) {
    ElMessage.error('复制失败')
  }
}

const customConfigs = ref<CustomConfig[]>([])
const selectedConfigId = ref<string>('')
const saveDialogVisible = ref(false)
const newConfigName = ref('')

// 加载本地配置
const loadCustomConfigs = async () => {
  try {
    const res = await tagApi().getRandomTagsConfig();
    customConfigs.value = res.data.data;
  } catch (error) {
    ElMessage.error('配置加载失败');
  }
}

// 打开保存对话框
const showSaveDialog = () => {
  if (!conditions.value.length) {
    ElMessage.warning('请先配置条件')
    return
  }
  newConfigName.value = ''
  saveDialogVisible.value = true
}

// 保存自定义配置 - 排除锁定状态和当前标签
const saveCustomConfig = async () => {
  if (!newConfigName.value.trim()) {
    ElMessage.warning('请输入配置名称');
    return;
  }

  try {
    const res = await tagApi().saveRandomConfig({
        name: newConfigName.value,
        // 保存时排除锁定状态和当前标签
        conditions: conditions.value.map(c => ({
          path: c.path,
          group: c.group,
          name: c.name,
          size: c.size
        }))
      })
    // 添加到当前配置列表
    customConfigs.value.push({
      id: res.data.id,
      name: newConfigName.value,
      conditions: conditions.value.map(c => ({
        path: c.path,
        group: c.group,
        name: c.name,
        size: c.size
      })),
      createTime: Date.now()
    });

    saveDialogVisible.value = false;
    ElMessage.success('配置保存成功');
  } catch (error) {
    ElMessage.error('保存失败: ' + (error.response?.data?.error || error.message));
  }
}

// 应用选中配置
const handleConfigSelect = async (configId: number) => {
  try {
    const res = await tagApi().getRandomTagsConfigById(configId)
    // 加载配置时初始化锁定状态为false
    conditions.value = res.data.conditions.map(c => ({
      ...c,
      path: [...c.path],
      locked: false,
      currentTags: [] // 初始化为空标签
    }));
  } catch (error) {
    ElMessage.error('加载配置失败');
  }
}
// 删除配置
const deleteConfig = async () => {
  if (!selectedConfigId.value) {
    ElMessage.warning('请选择要删除的配置');
    return;
  }

  try {
    await ElMessageBox.confirm('确定删除该配置吗？', '警告', {
      type: 'warning'
    });
    await tagApi().deleteRandomConfig(selectedConfigId.value);

    // 从当前列表中移除
    const index = customConfigs.value.findIndex(c => c.id === selectedConfigId.value);
    if (index !== -1) {
      customConfigs.value.splice(index, 1);
    }

    selectedConfigId.value = '';
    ElMessage.success('配置已删除');
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
}


// 暴露配置操作方法给父组件
defineExpose({
  getCurrentConfig: () => conditions.value,
  saveConfig: showSaveDialog,
  loadConfig: handleConfigSelect
})

onMounted(() => {
  loadCustomConfigs()
})
</script>

<style scoped lang="scss">
.random-tag-generator {
  padding: 20px;
  background: var(--el-fill-color-lighter);
  border-radius: 8px;

  .config-area {
    background: var(--el-bg-color);
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    border: 1px solid var(--el-border-color-lighter);

    .condition-item {
      display: flex;
      gap: 10px;
      margin-bottom: 15px;
      align-items: center;

      .cascader {
        flex: 2;
      }

      .size-input {
        flex: 1;
      }

      .remove-btn {
        flex-shrink: 0;
      }
    }

    .add-btn {
      width: 100%;
      margin-top: 10px;
    }
  }

  .action-area {
    text-align: center;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
    gap: 10px;
  }

  .result-area {
    .result-group {
      margin-bottom: 20px;
      background: var(--el-bg-color-overlay);
      border-radius: 8px;
      padding: 15px;
      border: 1px solid var(--el-border-color-lighter);

      .card-header {
        display: flex;
        align-items: center;
        gap: 10px;

        .group-name {
          font-weight: bold;
          color: var(--el-color-primary);
        }

        .sub-group {
          color: var(--el-color-success);
        }
      }

      .tag-list {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        padding-top: 10px;

        .tag-item {
          cursor: pointer;
          transition: all 0.3s;
          border: 1px solid var(--el-border-color);

          &:hover {
            transform: translateY(-2px);
            box-shadow: var(--el-box-shadow-light);
          }
        }

        .empty-tip {
          color: var(--el-text-color-placeholder);
          font-style: italic;
        }
      }
    }
  }
}
</style>
